﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace FgoDataCrawler.Utility
{
    public class CachedHttpClient
    {
        protected string CacheDir { get; set; }
        protected HttpClient HttpClient { get; set; }

        public CachedHttpClient(string cacheDir)
        {
            CacheDir = cacheDir;
            HttpClient = new HttpClient();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
        }

        public string GetAsString(string filename, string url, Encoding charset)
        {
            var cacheFile = CacheDir + "\\" + filename;
            string content = null;
            if (!File.Exists(cacheFile))
            {
                try
                {
                    var task = HttpClient.GetStringAsync(url);
                    content = task.Result;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    // var req = WebRequest.Create(url);
                    // req.Method = "GET";
                    // var resp = req.GetResponse();
                    // var stream = resp.GetResponseStream();
                    // StreamReader reader = new StreamReader(stream);
                    // content = reader.ReadToEnd();
                }
                File.WriteAllText(cacheFile, content, charset);
            }
            else
            {
                content = File.ReadAllText(cacheFile, charset);
            }
            return content;
        }

        public byte[] GetAsBytes(string filename, string url)
        {
            var cacheFile = CacheDir + "\\" + filename;
            byte[] data = null;
            if (!File.Exists(cacheFile))
            {
                data = HttpClient.GetByteArrayAsync(url).Result;
                File.WriteAllBytes(cacheFile, data);
            }
            else
            {
                data = File.ReadAllBytes(cacheFile);
            }
            return data;
        }
    }
}
